package org.springblade.common.tool;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统资源获取工具
 * @author 李家民
 */
public class SysResourceUtil {

	/**
	 * 截取小数点
	 * @param doubleValue 值
	 * @param radixPoint  小数点几位
	 * @return
	 */
	private static Double twoDecimal(double doubleValue, int radixPoint) {
		BigDecimal bigDecimal = new BigDecimal(doubleValue).setScale(radixPoint, RoundingMode.HALF_UP);
		return bigDecimal.doubleValue();
	}

	/**
	 * 获取当前系统性能情况
	 * @return
	 */
	public static Map<String, Object> getNowPerformance() {
		Map<String, Object> resMap = new HashMap<>();
		final long GB = 1024 * 1024 * 1024;
		OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
		String osJson = JSON.toJSONString(operatingSystemMXBean);
		// System.out.println("osJson is " + osJson);
		JSONObject jsonObject = JSON.parseObject(osJson);
		// double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
		double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
		Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
		Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
		// double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
		// double freeMemory = 1.0 * freePhysicalMemorySize / GB;
		double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;

		// StringBuilder result = new StringBuilder();
		// result.append("系统当前CPU占用率: ")
		//         .append(twoDecimal(systemCpuLoad, 2))
		//         .append("%，当前内存占用率：")
		//         .append(twoDecimal(memoryUseRatio, 2))
		//         .append("%，系统总内存：")
		//         .append(twoDecimal(totalMemory, 2))
		//         .append("GB，系统剩余内存：")
		//         .append(twoDecimal(freeMemory, 2))
		//         .append("GB，该进程占用CPU：")
		//         .append(twoDecimal(processCpuLoad, 2))
		//         .append("%");
		// System.out.println(result.toString());

		resMap.put("systemCpuLoad", twoDecimal(systemCpuLoad, 2));
		resMap.put("memoryUseRatio", twoDecimal(memoryUseRatio, 2));

		return resMap;
	}


}
